/** @format */

import React from 'react';
import {blog} from './index.styl';
import '@/assets/style/prim.css';
import {prism} from '@/assets/js/prism.js';
import {formateTime} from '@/util';
import MarkdownIt from 'markdown-it';
import trans from '@/api';
import {Link} from 'react-router-dom';

interface IProp {
  [props: string]: any;
}

interface IState {
  id: number;
  els: JSX.Element | null;
}

interface IArticle {
  id: number;
  title: string;
  category: string;
  markdown: string;
  html: string;
  release_date: string;
  visits: number;
}

class Blog extends React.Component<IProp, IState> {
  constructor(props: IProp, state: IState) {
    super(props);
    this.getDatas = this.getDatas.bind(this);
    this.getEls = this.getEls.bind(this);

    this.state = {
      id: parseInt((this.props as any).match.params.id),
      els: null,
    };
  }

  componentDidMount() {
    // 获取数据
    this.getEls();
  }

  componentDidUpdate() {
    prism();
  }

  async getDatas() {
    const param = {
      id: this.state.id,
    };

    const [err, articleData]: any = (await trans('getArticle', {params: param})) as IArticle;
    if (err) {
      return;
    }
    // 代码格式插件要求变量名必须要用驼峰命名
    articleData['release_date'] = formateTime(articleData['release_date'], 'YYYY-MM-DD');
    return articleData;
  }

  async getEls() {
    const articlesData = await this.getDatas();

    const els = (
      <div className={'container'}>
        <header>
          <h1>{articlesData.title}</h1>
        </header>
        <article>
          <article
            className={'markdown-body'}
            dangerouslySetInnerHTML={{__html: new MarkdownIt({html: true, breaks: true}).render(articlesData.markdown)}}
          />
          <div className="post-meta">
            <hr />
            <Link className={'category'} to={`/category/${articlesData.category}`}>
              {articlesData.category}
            </Link>
            <br />
            <time>{articlesData.release_date}</time>
          </div>
        </article>
      </div>
    );

    this.setState({els});
  }

  render(): JSX.Element {
    return <div className={`${blog}`}>{this.state.els}</div>;
  }
}

export default Blog;
